package com.qifenqian.turbot.module.ui.dish

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback
import com.chad.library.adapter.base.listener.OnItemDragListener
import com.qifenqian.turbot.R
import com.qifenqian.turbot.base.BaseActivity
import com.qifenqian.turbot.config.Constant
import com.qifenqian.turbot.module.adapter.restaurant.DishCategoryManageAdapter
import com.qifenqian.turbot.module.contract.DishContract
import com.qifenqian.turbot.module.entity.request.CategoryRequest
import com.qifenqian.turbot.module.entity.response.dish.CategoryEntity
import com.qifenqian.turbot.module.presenter.DishPresenter
import com.qifenqian.turbot.util.Lcat
import com.qifenqian.turbot.util.SpUtils
import kotlinx.android.synthetic.main.activity_dish_category_manage.*
import kotlinx.android.synthetic.main.dialog_edit_text.view.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.toast

class DishCategoryManageActivity : BaseActivity<DishPresenter, DishContract.View>(), DishContract.View {
    companion object {
        fun startThis(context: Context) {
            val intent = Intent(context, DishCategoryManageActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun bindLayoutId(): Int {
        return R.layout.activity_dish_category_manage
    }

    override fun bindPresenter(): DishPresenter? {
        return DishPresenter(this, this)
    }

    override fun initial() {
        mPresenter!!.getCategoryList()
        rv_dish_category_manage.layoutManager = LinearLayoutManager(this)
        mDishCategoryManageAdapter = DishCategoryManageAdapter(mCategoryEntities)
        rv_dish_category_manage.adapter = mDishCategoryManageAdapter
        val itemDragAndSwipeCallback = ItemDragAndSwipeCallback(mDishCategoryManageAdapter)
        val itemTouchHelper = ItemTouchHelper(itemDragAndSwipeCallback)
        itemTouchHelper.attachToRecyclerView(rv_dish_category_manage)
        mDishCategoryManageAdapter!!.enableDragItem(itemTouchHelper)
        mDishCategoryManageAdapter!!.setOnItemDragListener(object : OnItemDragListener {
            var targetCategoryEntity: CategoryEntity? = null
            override fun onItemDragStart(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                //记录开始的位置
                targetCategoryEntity = mCategoryEntities[pos]
            }

            override fun onItemDragMoving(source: RecyclerView.ViewHolder?, from: Int, target: RecyclerView.ViewHolder?, to: Int) {
            }

            override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder?, pos: Int) {
                //先移除需要移动前的对象,再将该对象添加到移动后的位置
                mCategoryEntities.remove(targetCategoryEntity)
                mCategoryEntities.add(pos, targetCategoryEntity!!)
            }
        })
        btn_dish_category_manage_add.setOnClickListener {
            showCategoryAddDialog()
        }
        mDishCategoryManageAdapter!!.setOnItemChildClickListener(object : DishCategoryManageAdapter.OnItemChildClickListener {
            override fun onEditClick(position: Int) {
                showCategoryEditDialog(position)
            }

            override fun onDeleteClick(position: Int) {
                alert("确认删除该类别吗?") {
                    positiveButton("确定") {
                        mPresenter!!.deleteCategory(mCategoryEntities[position].id, position)
                    }
                    negativeButton("取消") {
                        it.dismiss()
                    }
                }.show()
            }
        })
    }

    private var mCategoryEntities = mutableListOf<CategoryEntity>()

    private var mDishCategoryManageAdapter: DishCategoryManageAdapter? = null

    override fun onBackPressed() {
        val dishTypes: MutableList<CategoryRequest.DishType> = mutableListOf()
        for (i in 0 until mCategoryEntities.size) {
            mCategoryEntities[i].dishTypeOrder = i
            val dishType = CategoryRequest.DishType(mCategoryEntities[i].id, mCategoryEntities[i].dishTypeName, i)
            dishTypes.add(dishType)
        }
        val request = CategoryRequest(SpUtils.getInstance().getInt(Constant.SP_KEY_RESTAURANT_ID, -1, Constant.SP_ACCOUNT), dishTypes)
        mPresenter!!.saveCategory(request)

    }

    private var mCategoryAddDialog: Dialog? = null
    private fun showCategoryAddDialog() {
        mCategoryAddDialog = Dialog(this)
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null)
        mCategoryAddDialog!!.setContentView(view)
        mCategoryAddDialog!!.show()
        view.tv_dialog_edit_title.text = "添加菜品分类"
        view.btn_dialog_edit_cancel.setOnClickListener { mCategoryAddDialog!!.dismiss() }
        view.btn_dialog_edit_ok.setOnClickListener {
            if (view.et_dialog_edit_content.text.toString().isEmpty()) {
                toast("输入内容不能为空")
                return@setOnClickListener
            }
            mPresenter!!.addCategory(view.et_dialog_edit_content.text.toString())
        }
    }

    private var mCategoryEditDialog: Dialog? = null
    private fun showCategoryEditDialog(position: Int) {
        mCategoryEditDialog = Dialog(this)
        val view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null)
        mCategoryEditDialog!!.setContentView(view)
        mCategoryEditDialog!!.show()
        view.tv_dialog_edit_title.text = "编辑菜品分类"
        view.et_dialog_edit_content.setText(mCategoryEntities[position].dishTypeName)
        view.btn_dialog_edit_cancel.setOnClickListener { mCategoryEditDialog!!.dismiss() }
        view.btn_dialog_edit_ok.setOnClickListener {
            if (view.et_dialog_edit_content.text.toString().isEmpty()) {
                toast("输入内容不能为空")
                return@setOnClickListener
            }
            mPresenter!!.editCategory(view.et_dialog_edit_content.text.toString(), mCategoryEntities[position].id, position)
        }
    }

    override fun getCategoryListResult(isSuccess: Boolean, code: Int, msg: String?, categoryEntities: List<CategoryEntity>?) {
        if (isSuccess) {
            mCategoryEntities.clear()
            mCategoryEntities.addAll(categoryEntities as MutableList)
            mDishCategoryManageAdapter!!.notifyDataSetChanged()
        } else {
            finish()
            toast(msg!!)
        }
    }

    override fun addCategoryResult(isSuccess: Boolean, code: Int, msg: String?, categoryEntity: CategoryEntity?) {
        if (isSuccess) {
            mCategoryEntities.add(categoryEntity!!)
            mDishCategoryManageAdapter!!.notifyDataSetChanged()
            if (mCategoryAddDialog != null) {
                mCategoryAddDialog!!.dismiss()
            }
        }
        toast(msg!!)
    }

    override fun editCategoryResult(isSuccess: Boolean, code: Int, msg: String?, position: Int, newCategory: String?) {
        if (isSuccess) {
            Lcat.a("mCategoryEntities", mCategoryEntities)
            mCategoryEntities[position].dishTypeName = newCategory!!
            mDishCategoryManageAdapter!!.notifyDataSetChanged()
            mCategoryEditDialog!!.dismiss()
        }
        toast(msg!!)
    }

    override fun deleteCategoryResult(isSuccess: Boolean, code: Int, msg: String?, position: Int) {
        if (isSuccess) {
            mCategoryEntities.removeAt(position)
            mDishCategoryManageAdapter!!.notifyItemRemoved(position)
        }
        toast(msg!!)
    }

    override fun saveCategoryResult(isSuccess: Boolean, code: Int, msg: String?) {
        toast(msg!!)
        super.onBackPressed()

    }
}
